﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.IO;

public partial class Manager_SysClass : System.Web.UI.PageEx
{
    private string strPageCode = "P0000A";
    private string strLoginResult = string.Empty;
    private short sClassType = 0;
    private string strSelectLang = "CN";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!DalEx.DbManagerEx.CheckLoginRight(UserType, UserId, strPageCode, ref strLoginResult))
        {
            FineUI.Alert.Show(strLoginResult, FineUI.MessageBoxIcon.Warning);
            Response.Redirect("Login.aspx");
        }
        string strClassType = Convert.ToString(Request.QueryString["Type"]);
        switch (strClassType)
        { 
            case "Prod":
                sClassType = 1;
                winForm.Title = "新增（编辑）产品类别";
                break;
            case "Course":
                sClassType = 2;
                winForm.Title = "新增（编辑）课程体系类别";
                break;
            default:
                sClassType = 0;
                winForm.Title = "新增（编辑）文章类别";
                break;
        }
        if (!Page.IsPostBack)
        {
            fuBgImage.Visible = sClassType == 1;
            ViewState["SelectLang"] = strSelectLang;
            DataBinds();
            btnReset.OnClientClick = sfObject.GetResetReference();
        }
    }
    private void DataBinds()
    {
        strSelectLang = Convert.ToString(ViewState["SelectLang"]);
        DataSet ds = null;
        List<Model.DbClass> lstClass = new List<Model.DbClass>();
        DalEx.DbClassEx.GetClassList(0, " and cType=" + sClassType, ref lstClass, strSelectLang);
        ddlUpClass.DataSource = lstClass;
        ddlUpClass.DataValueField = "CId";
        ddlUpClass.DataTextField = "CName";
        ddlUpClass.DataSimulateTreeLevelField = "CLevel";
        ddlUpClass.DataBind();
        ddlUpClass.Items.Insert(0, new FineUI.ListItem("顶级菜单", "0"));

        gridList.DataSource = lstClass;
        gridList.DataBind();

        btnCNVer.Enabled = strSelectLang.CompareTo("EN") == 0;
        btnENVer.Enabled = strSelectLang.CompareTo("CN") == 0;
    }
    protected void btnCNVer_Click(object sender, EventArgs e)
    {
        ViewState["SelectLang"] = "CN";
        DataBinds();
    }
    protected void btnENVer_Click(object sender, EventArgs e)
    {
        ViewState["SelectLang"] = "EN";
        DataBinds();
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        txtClassName.Label = "类别名称";
        txtNotes.Label = "备注信息";
        txtKeywords.Label = "优化站点关键词";
        txtDescription.Label = "优化站点关键词";

        strSelectLang = Convert.ToString(ViewState["SelectLang"]);
        List<int> lstSelectRowId = WebBase.Comm.GetGridSeleteRowId(gridList);
        if (lstSelectRowId.Count == 1)
        {
            int iSelectId = lstSelectRowId[0];
            Model.DbClass dbClass = DalEx.DbClassEx.Select(iSelectId,strSelectLang);
            if (dbClass != null)
            {
                txtClassName.Text = dbClass.CName;
                txtNotes.Text = dbClass.CNote;
                txtOrder.Text = dbClass.COrder.ToString();
                txtKeywords.Text = dbClass.CKeywords;
                txtDescription.Text = dbClass.CDescription;
                cboxStatus.Checked = Convert.ToBoolean(dbClass.CStatus);
                ddlUpClass.SelectedValue = Convert.ToString(dbClass.CUpId);
                hfClassId.Text = dbClass.CId.ToString();
            }
            winForm.Popup = true;
        }
        else if (lstSelectRowId.Count > 1)
        {
            FineUI.Alert.Show("抱歉，请不要选择多项进行编辑！", FineUI.MessageBoxIcon.Warning);
        }
        else
        {
            sfObject.Reset();
            winForm.Popup = true;
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        strSelectLang = Convert.ToString(ViewState["SelectLang"]);
        int iUpClassId = 0;
        int iClassOrder = 0;
        int iClassId = 0;
        string strClassName = txtClassName.Text.Trim();
        string strClassNote = txtNotes.Text.Trim();
        string strKeywords = txtKeywords.Text.Trim();
        string strDescription = txtDescription.Text.Trim();
        int.TryParse(txtOrder.Text.Trim(), out iClassOrder);
        short sStatus = Convert.ToInt16(cboxStatus.Checked);
        int.TryParse(ddlUpClass.SelectedValue, out iUpClassId);
        int.TryParse(hfClassId.Text, out iClassId);
        #region 上传文件处理
        string fileName = string.Empty;
        if (fuImage.HasFile)
        {
            fileName = fuImage.ShortFileName;
            fileName = fileName.Replace(":", "_").Replace(" ", "_").Replace("\\", "_").Replace("/", "_");
            fileName = DateTime.Now.Ticks.ToString() + "_" + fileName;
            //检查目录是否存在，不存在则创建
            if (!Directory.Exists(Server.MapPath("~/upload/")))
                Directory.CreateDirectory(Server.MapPath("~/upload/"));
            //文件保存
            fuImage.SaveAs(Server.MapPath("~/upload/" + fileName));

            fileName = ResolveUrl("~/upload/" + fileName);
        } 
        string fileName1 = string.Empty;
        if (fuBgImage.HasFile)
        {
            fileName1 = fuBgImage.ShortFileName;
            fileName1 = fileName1.Replace(":", "_").Replace(" ", "_").Replace("\\", "_").Replace("/", "_");
            fileName1 = DateTime.Now.Ticks.ToString() + "_" + fileName1;
            //检查目录是否存在，不存在则创建
            if (!Directory.Exists(Server.MapPath("~/upload/")))
                Directory.CreateDirectory(Server.MapPath("~/upload/"));
            //文件保存
            fuBgImage.SaveAs(Server.MapPath("~/upload/" + fileName1));

            fileName1 = ResolveUrl("~/upload/" + fileName1);
        }
        #endregion
        string strResult = string.Empty;
        Model.DbClass dbClass = new Model.DbClass();
        dbClass.CName = SqlHelper.String(strClassName);
        dbClass.CNote = SqlHelper.String(strClassNote);
        dbClass.CKeywords = SqlHelper.String(strKeywords);
        dbClass.CDescription = SqlHelper.String(strDescription);
        dbClass.CDatetime = DateTime.Now;
        dbClass.CType = sClassType;
        dbClass.CUpId = iUpClassId;
        dbClass.CId = iClassId;
        dbClass.COrder = iClassOrder;
        dbClass.CStatus = sStatus;
        dbClass.CLevel = 0;
        dbClass.CPic = fileName;
        dbClass.CBgImg = fileName1;
        int iResult = DalEx.DbClassEx.InsertEx(dbClass, ref strResult);
        if (iResult > 0)
        {
            Model.DbActionLog actionLog = new Model.DbActionLog();
            actionLog.AUId = UserId.ToString();
            actionLog.ADateTime = DateTime.Now;
            actionLog.ANote = "操作类别【" + dbClass.CName + "】，" + strResult;
            actionLog.AIpaddress = WebBase.GetClientIP.getIPAddress2Num().ToString();
            actionLog.AOS = WebBase.Comm.GetOS;
            actionLog.ABrowse = WebBase.Comm.GetUserBrowser;
            Dal.DbActionLogDal.Insert(actionLog);
            sfObject.Reset();
            DataBinds();
            FineUI.Alert.Show(strResult, FineUI.MessageBoxIcon.Information);
        }
        else
        {
            FineUI.Alert.Show(strResult, FineUI.MessageBoxIcon.Warning);
        }
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        List<string> lstFiles = new List<string>();
        List<int> lstSelectRowId = WebBase.Comm.GetGridSeleteRowId(gridList);
        if (lstSelectRowId.Count > 0)
        {
            DataSet ds = null;
            ArrayList lstSql = null;
            lstSql = new ArrayList();
            Model.DbClass _Class = null;
            foreach (int iSelectId in lstSelectRowId)
            {
                _Class = DalEx.DbClassEx.Select(iSelectId);
                lstFiles.Add(_Class.CPic);
                ds = DalEx.DbClassEx.Select(" and cUpId='" + _Class.CId + "'");
                if (SqlHelper.HasRow(ds))
                {
                    lstSql.Clear();
                }
                else
                {
                    lstSql.Add("delete from dbClass where cId=" + iSelectId);
                    //lstSql.Add("delete from dbEnClass where cId=" + iSelectId);
                }
            }
            int iResult = SqlHelper.ExecSql(lstSql);
            if (iResult > 0)
            {
                //删除类别略图
                //try
                //{
                //    foreach (string strFilePath in lstFiles)
                //        File.Delete(Server.MapPath(strFilePath));
                //}
                //catch { }
                DataBinds();
                FineUI.Alert.Show("数据删除成功！", FineUI.MessageBoxIcon.Information);
            }
            else
            {
                FineUI.Alert.Show("请检查是否还有下级类别！", FineUI.MessageBoxIcon.Warning);
            }
        }
        else
        {
            FineUI.Alert.Show("请选择要删除项！", FineUI.MessageBoxIcon.Warning);
        }
    }
    protected void gridList_RowCommand(object sender, FineUI.GridCommandEventArgs e)
    {
        Dictionary<int, Dictionary<int, string>> modifiedDict = gridList.GetModifiedDict();
        int iSelectId = 0;
        string strCommandName = e.CommandName.ToString();
        string strResult = string.Empty;
        if (!string.IsNullOrEmpty(strCommandName))
        {
            int iSelectIndexId = e.RowIndex;
            string strSelectId = gridList.Rows[iSelectIndexId].DataKeys[0].ToString();
            Int32.TryParse(strSelectId, out iSelectId);
            switch (strCommandName)
            {
                case "Delete":
                    if (DalEx.DbClassEx.DeleteEx(iSelectId, ref strResult) > 0)
                    {
                        Model.DbActionLog actionLog = new Model.DbActionLog();
                        actionLog.AUId = UserId.ToString();
                        actionLog.ADateTime = DateTime.Now;
                        actionLog.ANote = "类别(" + iSelectId + ")资料已删除";
                        actionLog.AIpaddress = WebBase.GetClientIP.getIPAddress2Num().ToString();
                        actionLog.AOS = WebBase.Comm.GetOS;
                        actionLog.ABrowse = WebBase.Comm.GetUserBrowser;
                        Dal.DbActionLogDal.Insert(actionLog);
                        DataBinds();
                        FineUI.Alert.Show(strResult, FineUI.MessageBoxIcon.Information);
                    }
                    else
                    {
                        FineUI.Alert.Show(strResult, FineUI.MessageBoxIcon.Warning);
                    }
                    break;
                case "AddEngLish":
                    strSelectLang = "EN";
                    ViewState["SelectLang"] = strSelectLang;
                    winForm.Title = "产品类型（英文版）编辑(提示：带*号的为英文版显示内容项)";
                    txtClassName.Label = "类别名称(*)";
                    txtNotes.Label = "备注信息(*)";
                    txtKeywords.Label = "优化站点关键词(*)";
                    txtDescription.Label = "优化站点关键词(*)";
                    Model.DbClass dbClass = DalEx.DbClassEx.Select(iSelectId, strSelectLang);
                    if (dbClass == null)
                        dbClass = DalEx.DbClassEx.Select(iSelectId, "CN");
                    if (dbClass != null)
                    {
                        txtClassName.Text = dbClass.CName;
                        txtNotes.Text = dbClass.CNote;
                        txtOrder.Text = dbClass.COrder.ToString();
                        txtKeywords.Text = dbClass.CKeywords;
                        txtDescription.Text = dbClass.CDescription;
                        cboxStatus.Checked = Convert.ToBoolean(dbClass.CStatus);
                        ddlUpClass.SelectedValue = Convert.ToString(dbClass.CUpId);
                        hfClassId.Text = dbClass.CId.ToString();
                    }
                    winForm.Popup = true;
                    break;
            }
        }
    }
    protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
    {
        int iPageSize = 20;
        int.TryParse(ddlPageSize.SelectedValue, out iPageSize);
        gridList.PageSize = iPageSize;
        DataBinds();
    }
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        DataBinds();
    }
    protected void gridList_RowDataBound(object sender, FineUI.GridRowEventArgs e)
    {
        Model.DbClass drv = (Model.DbClass)gridList.Rows[e.RowIndex].DataItem;
        Label lblClass = (Label)gridList.Rows[e.RowIndex].FindControl("lblShowUpClassName");
        Model.DbClass dbClass = DalEx.DbClassEx.Select(Convert.ToInt32(lblClass.Text));
        if (dbClass != null)
        {
            lblClass.Text = dbClass.CName;
        }
        else
        {
            lblClass.Text = "/";
        }
    }
}
